<template>
  <div style="margin:10px 20px">
    <!-- 顶级筛选 -->
    <div class="top-filter">
      <div class="tab-bar">
        <span class="tab active">问卷库</span>
      </div>
      <div class="search-container">
        <div class="search-input-wrapper">
          <input v-model="searchQuery" placeholder="搜索问卷" class="search-input" />
          <img src="@/assets/picture/find.png" alt="搜索" class="search-icon" @click="filterSurveys" />
        </div>
        <button @click="openCreateDialog" class="action-button">新建问卷</button>
      </div>
    </div>

    <!-- 问卷列表 -->
    <div class="survey-list">
      <ul class="quiz-list">
        <li v-for="survey in paginatedSurveys" :key="survey.paper_id" class="quiz-item">
          <div class="quiz-details">
            <span><strong>{{ survey.paper_title }}</strong></span>
            <span>试题数: {{ survey.qs_cnt }}  |  更新时间: {{ survey.create_time }}</span>
          </div>
          <div class="quiz-buttons">
            <button class="btn action-btn" @click="editSurvey(survey.paper_id)">编辑</button>
            <button 
              class="btn action-btn delete-btn" 
              @click.stop="techdeleteSurvey(survey.survey_id)"> 
              删除
            </button>
            <!-- 新增的选择按钮 -->
            <button 
              v-if="isSelectMode"
              class="btn action-btn select-mode-btn"
              :class="{ 'selected-btn': selectedSurvey === survey.survey_id }"
              @click.stop="selectPaper(survey)">
              {{ selectedSurvey === survey.survey_id ? '取消' : '选择' }}
            </button>
          </div>
        </li>
      </ul>
    </div>
    <div v-if="selectedSurvey" class="selected-paper-info">
      选中的问卷 ID: {{ selectedSurvey }}
    </div>

    <!-- 分页组件 -->
    <PagiNation
      :currentPage="currentPage"
      :totalPages="totalPages"
      @page-change="handlePageChange"
    />

    <!-- 新建问卷弹窗 -->
    <div v-if="createDialogVisible" class="create-dialog">
      <div class="dialog-content">
        <h4>新建问卷</h4>
        <input v-model="newSurvey.paper_title" placeholder="输入问卷标题" class="input-field" />
        <textarea v-model="newSurvey.paper_content" placeholder="输入问卷内容" class="input-field"></textarea>
        <div class="dialog-actions">
          <button class="action-btn" @click="createDialogVisible = false">取消</button>
          <button class="action-btn" @click="submitNewSurvey">确认</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ElMessage, ElMessageBox } from 'element-plus';
import { ref, computed, onMounted } from 'vue';
import { fetchSurveys, createSurvey,deleteSurvey } from '@/services/api';
import PagiNation from '@/components/PagiNation.vue';
import { useRouter } from 'vue-router';

export default {
  name: 'SurveyList',
  components: { PagiNation },
   props: {
    isSelectMode: {
      type: Boolean,
      default: false
    },
  },
  setup(props, { emit }) {
    const techId = ref(Number(localStorage.getItem('id')));  
    const semId = ref(Number(localStorage.getItem('selectedClassId')));  
    const router = useRouter();
    const surveys = ref([]);
    const filteredSurveys = ref([]);
    const searchQuery = ref('');
    const currentPage = ref(1);
    const itemsPerPage = 8;
    const createDialogVisible = ref(false);
    const newSurvey = ref({
      paper_title: '',
      paper_content: '',
      sem_id: semId,
      tech_id: techId
    });
    
    // 选中的问卷 paperId
    const selectedSurvey = ref(null);

    // 获取问卷数据
    const fetchSurveyData = async () => {
      try {
        const res = await fetchSurveys(techId.value);
        if (res.data.status === 1 && res.data.code === 'S0000') {
          surveys.value = res.data.data;
          filteredSurveys.value = surveys.value;
        } else {
          console.error('获取问卷失败');
        }
      } catch (err) {
        console.error('接口请求错误');
      }
    };
  const selectPaper = (survey) => {
        emit('paper-selected', {
    survey_id: survey.survey_id,  // 确保字段名正确
    paper_title: survey.paper_title
  });
    };
    // 筛选问卷
    const filterSurveys = () => {
      if (!searchQuery.value) {
        filteredSurveys.value = surveys.value;
      } else {
        const query = searchQuery.value.toLowerCase();
        filteredSurveys.value = surveys.value.filter(s => s.paper_title.toLowerCase().includes(query));
      }
      currentPage.value = 1;
    };

    // 分页
    const paginatedSurveys = computed(() => {
      const start = (currentPage.value - 1) * itemsPerPage;
      return filteredSurveys.value.slice(start, start + itemsPerPage);
    });

    const totalPages = computed(() => {
      return Math.ceil(filteredSurveys.value.length / itemsPerPage) || 1;
    });

    const handlePageChange = (newPage) => {
      currentPage.value = newPage;
    };

    const openCreateDialog = () => {
      newSurvey.value = {
        paper_title: '',
        paper_content: '',
        sem_id:semId ,
        tech_id: techId
      };
      createDialogVisible.value = true;
    };

    const submitNewSurvey = async () => {
      try {
        const res = await createSurvey(newSurvey.value);
        if (res.data.status === 1 && res.data.code === 'S0000') {
          createDialogVisible.value = false;
          fetchSurveyData();
        } else {
          console.error('创建失败');
        }
      } catch (e) {
        console.error('接口调用失败');
      }
    };

    const editSurvey = (paperId) => {
      router.push(`/edit-survey/${paperId}`);
    };

    const techdeleteSurvey = async (surveyId) => {
      try {
        await ElMessageBox.confirm('确认删除该问卷吗？', '警告', {
          confirmButtonText: '删除',
          cancelButtonText: '取消',
          type: 'warning',
        });
        
        const response = await deleteSurvey(surveyId);
        if (response.data.status === 1) {
          ElMessage.success('删除成功！');
          fetchSurveyData(); // 重新加载问卷列表
        }
      } catch (error) {
        // 用户取消操作自动捕获
      }
    };

    // 选择问卷的逻辑
    const selectSurvey = (paperId) => {
      if (selectedSurvey.value === paperId) {
        selectedSurvey.value = null; // 如果已选中，取消选择
      } else {
        selectedSurvey.value = paperId; // 否则选择当前问卷
      }
    };

    onMounted(() => {
      fetchSurveyData();
    });

    return {
      surveys,
      searchQuery,
      filteredSurveys,
      paginatedSurveys,
      totalPages,
      currentPage,
      handlePageChange,
      filterSurveys,
      editSurvey,
      techdeleteSurvey,
      createDialogVisible,
      openCreateDialog,
      submitNewSurvey,
      newSurvey,
      selectedSurvey,  // 返回 selectedSurvey 用于绑定和显示选中的问卷
      selectSurvey,     // 选择问卷的函数
       selectPaper
    };
  }
};
</script>

<style scoped>
.top-filter {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.tab-bar {
  display: flex;
  padding: 10px;
}

.tab {
  padding: 10px 20px;
  cursor: pointer;
}

.tab.active {
  border-bottom: 2px solid #244382;
  color: #244382;
  font-weight: bold;
}

.search-container {
  display: flex;
  align-items: center;
}

.search-input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
}

.search-input {
  padding: 8px 12px;
  border: 1px solid #ccc;
  border-radius: 20px;
  min-width: 200px;
  font-size: 16px;
  padding-right: 35px;
}

.search-icon {
  position: absolute;
  right: 10px;
  cursor: pointer;
  width: 20px;
  height: 20px;
}

.action-button {
  background-color: #125aa2;
  color: white;
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  margin-left: 10px;
  cursor: pointer;
}

.action-button:hover {
  background-color: #0e4b8a;
}

.quiz-list {
  list-style: none;
  padding: 0;
  width: 100%;
}

.quiz-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  margin-bottom: 12px;
  background: white;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  transition: all 0.3s;
}

.quiz-details {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.quiz-buttons {
  display: flex;
  gap: 8px;
  min-width: 180px;
  justify-content: flex-end;
}

.btn.action-btn {
  padding: 7px 12px;
  border-radius: 4px;
  font-size: 13px;
  background: #f6f7fb;
  color: #125aa2;
  border: 1px solid #d9e0eb;
  transition: all 0.2s;
}

.btn.action-btn:hover {
  background: #e1e7f4;
}

.btn.delete-btn {
  background: #fff2f2 !important;
  color: #ff4d4d !important;
  border-color: #ffd6d6 !important;
}

.btn.delete-btn:hover {
  background: #ffe6e6 !important;
}

.selected-paper-info {
  font-size: 14px;
  color: #666;
  margin-top: 20px;
  font-weight: bold;
}

.selected-btn {
  background-color: #4CAF50;  /* 选中时变成绿色 */
  color: white;
}

.create-dialog {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: white;
  padding: 20px;
  border-radius: 10px;
   border: 1px solid #ddd;
}
.dialog-actions button:first-child {
  background-color: #999 !important;
  margin-right: 10px;
}

.dialog-actions button:first-child:hover {
  background-color: #666 !important; 
}

.dialog-actions button:last-child {
  background-color: #125aa2;  
  margin-left: 10px;
}
.dialog-content {
  width: 300px;
  margin: 20px;
}

.input-field {
  width: 93%;
  padding: 10px;
  margin: 10px 0;
  border: 1px solid #ddd;
  border-radius: 5px;
}

.dialog-actions {
  display: flex;
  justify-content: space-between;
}

.dialog-actions button {
  width: 40%;
  padding: 10px;
  background-color: #125aa2;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.dialog-actions button:hover {
  background-color: #0e4b8a;
}
.btn.action-btn {
  background-color: #125AA2;
  color: #fff;
  padding: 8px 12px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.btn.action-btn:hover {
  background-color: #3987d4;
}

.btn.delete-btn {
  background-color: #ff4d4d !important;
  color: white !important;
}

.btn.delete-btn:hover {
  background-color: #ff6666 !important;
}

.selected-btn {
  background-color: #4CAF50 !important;
  color: white !important;
}


.btn.action-btn[class*="selected-btn"] {
  background-color: #eee !important;
  color: #666 !important;
}

.quiz-buttons {
  gap: 8px;
  min-width: 200px; /* 适当加宽按钮区域 */
}


</style>
